#include "game.h"
#include <GL/glut.h>

void Game::init(string filePath)
{
	Level level;
	level.loadLevel("./maps/"+filePath);
	level.setFilePath(filePath);
	level.restoreLevel();

	//init game
	levelFilePath=level.getLevelFilePath();
	name=level.getName();
	description=level.getDescription();
	previewFilePath=level.getPreviewFilePath();
	goalScore=level.getGoalScore();

	tShipState=CAN_SELECT_SHIP;

	//init zone
	zone.getMap()=level.getMap();
	zone.getIslands()=level.getIslands();
	zone.getPacks()=level.getPacks();
	zone.getRoutes()=level.getRoutes();
	zone.getMap().fromPpmValuestoMapValues();

	zone.calculateMap();

	//TODO init p1
	for(unsigned int i=0;i<level.getShips().size();i++)
	{
		if(level.getShips()[i].getPlayer()==1)
		{
			player[0].pushBattleShip(level.getShips()[i]);
		}
	}
	if(level.getPorts().size()>0)
	{
		cout << level.getPorts()[0].getPlayerId() << endl;
		player[0].setPort(level.getPorts()[0]);
	}
	player[0].setCurrents();

	//TODO init p2
	for(unsigned int i=0;i<level.getShips().size();i++)
	{
		if(level.getShips()[i].getPlayer()==2)
		{
			player[1].pushBattleShip(level.getShips()[i]);
		}
	}
	if(level.getPorts().size()>1)
	{
		cout << level.getPorts()[1].getPlayerId() << endl;
		player[1].setPort(level.getPorts()[1]);
	}
	player[1].setCurrents();
}

void Game::resetStates()
{
	tShipState=CAN_SELECT_SHIP;
}

bool Game::isStatic()
{
	return player[0].isStatic() && player[1].isStatic();
}


pair<float,float> Game::getCurrentShipsPosition()
{
	return player[playerId].getCurrentShipsPosition();
}

float Game::getCurrentShipsOrientation()
{
	return player[playerId].getCurrentShipsOrientation();
}

void Game::setCurrentShip(int shipId)
{
	if(tShipState==CAN_SELECT_SHIP)
		player[playerId].setCurrentShip(shipId);
}

void Game::moveCurrentShip(int mode)
{
	if(mode==-1)
		player[playerId].calculateCurrentShipsPosition();
	else
	{
		tShipState=CAN_FIRE_AND_MOVE;
		player[playerId].moveCurrentShip(mode);
	}
}

void Game::selectNextShip()
{
	if(tShipState!=CAN_SELECT_SHIP)
	{
		cout << "You can't select a ship state is at " << tShipState << endl;
		return;
	}
	else
	{
		cout << "I'll select the next ship" << endl;
		player[playerId].selectNextShip();
	}
}

void Game::resetTurn()
{
	tShipState=0;
}

void Game::drawInfo()
{
	player[0].drawInfo(0,1);
	player[1].drawInfo(700,2);
}

void Game::draw(int mode,int isPicking)
{
	glPushName(0); // It is popped at player[0].draw() function
	player[0].draw((playerId+1)%2,zone.getMap().getSeaLevel()*zone.getMap().getMapDimensionZ()/255.0,mode,isDay); //Calculate Whose Turn Is This
	glPushName(1); // It is popped at player[1].draw() function
	player[1].draw(playerId,zone.getMap().getSeaLevel()*zone.getMap().getMapDimensionZ()/255.0,mode,isDay); //Calculate Whose Turn Is This
	if(!isPicking)
		zone.draw();
}


